#pragma once
#include <cstdio>
#include <iostream>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "Common.hpp"
#include <set>
using namespace LogModule;
class Command {
public:
    Command() {
        _WriteListCommand.insert("ls");
        _WriteListCommand.insert("pwd");
        _WriteListCommand.insert("ls -l");
        _WriteListCommand.insert("whoami");
        _WriteListCommand.insert("touch haha.txt");
    }
    bool IsSafeCommend(const std::string command) {
        return _WriteListCommand.find(command) != _WriteListCommand.end();
    }
    std::string Execute(const std::string &cmd, const InetAddr& addr) {
        // 看看是不是白名单的命令
        if(!IsSafeCommend(cmd)) {
            return std::string("你是一个坏人！");
        }
        std::string user = addr.StringAddr();
        FILE* f = popen(cmd.c_str(), "r");
        if(f == nullptr) {
            return std::string("执行的命令不存在：") + cmd;
        }
        std::string ret;
        char buffer[1024];
        while (fgets(buffer, sizeof(buffer), f)) {
            ret += buffer;
        }
        pclose(f);
        std::string res = user + "成功执行命令：" + ret;
        LOG(LogLevel::DEBUG) << res;
        return res;
    }
    ~Command() {}
private:
    std::set<std::string> _WriteListCommand;
};